import { _decorator, Animation, Collider2D, Component, Contact2DType, find, IPhysics2DContact, log, Node, Vec3 } from 'cc';
import { GlobalEvent } from './tool/GlobalEventManager';
import { AudioManager } from './tool/AudioManager';
import { GameManager } from './GameManager';
const { ccclass, property } = _decorator;

@ccclass('diren')
export class diren extends Component {
    //这个是敌人
    //血量
    private _hp: number = 3;

    private isMoveing: boolean = false; // 核心：一个简单的标志位
    private isAttacking: boolean = false; // 攻击标志位

    private isStart: boolean = false; // 开始标志位
    //移动速度
    private moveSpeed: number = 30;

     //保存动画组件
    private _animation: Animation | null = null;


    // @_decorator.property(Node)
    private target: Node | null = null;  // 绑定目标精灵




    private attackCollider: Collider2D = null;
    private isAttsacking: boolean = false;
    
    //是否完成事件注册
    private hasRegistered: boolean = false; 
    onLoad() {
        // 获取Animation组件
        this._animation = this.node.getComponent(Animation);

         // 获取玩家身上的碰撞体组件
        this.attackCollider = this.getComponent(Collider2D);
        
        if (this.attackCollider) {
            // 监听碰撞事件
            this.attackCollider.on(Contact2DType.BEGIN_CONTACT, this.onAttackHit, this);
        }


        if (!this.hasRegistered) { 
            this.hasRegistered = true;
            // 下面监听所有事件
            GlobalEvent.on('hitEnemy', (data: any)=>{
                this.hurt(1);
            }, this);
        }
       

    }

    // 攻击
    public pi(arg: number) {
      this.isAttsacking=true
        let collider = this.target.getComponent(Collider2D);
        if (collider) {
            collider.enabled = true;
        }
    }
    public piEnd(arg: number) {
      this.isAttsacking=false
        let collider = this.target.getComponent(Collider2D);
        if (collider) {
            collider.enabled = false;
        }
    }


    // 碰撞检测：刀碰到敌人
    private onAttackHit(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
       if(!this.isAttsacking) return
        // console.log(`💥 击中玩家: ${contact}`,selfCollider.node.name =='Skeleton');
        AudioManager.instance.playSFX('sound/duan');

        if(selfCollider.node.name =='Skeleton'){
            GlobalEvent.emit('hitPlayer', 1);
        }
    }



    start() {
        this.scheduleOnce(function() {
            // log('敌人开始移动2',this._animation.clips)
            this.isStart = true;
            if (this._animation && this._animation.clips.some(clip => clip.name === 'run')) {
                // log('播放动画')
                this._animation.play('run'); 
            }
        }, 2);
        this.target=find('Canvas/player/body');
        const randomInt = Math.floor(Math.random() * (40 - 20 + 1)) + 20;
        this.moveSpeed = randomInt;
    }

    hurt(num: number) {
        if (this._animation && this._animation.clips.some(clip => clip.name === 'hit')) {
            this._animation.on(Animation.EventType.FINISHED, () => {
                if (!this.isMoveing) {
                    this._animation.play('zhan');
                }else{
                    this._animation.play('run');
                }
            });
            

            this._animation.play('hit');
        }
        this._hp -= num;
        if (this._hp <= 0) {
            GlobalEvent.emit('dieEnemy', 1);
            this.node.destroy();
        }
    }
    gongji() { 
        if(GameManager.instance.getGameStatus() != 1) return;
        if(!this.isAttacking){
            this.isAttacking = true;
            if (this._animation && this._animation.clips.some(clip => clip.name === 'gong')) {
                this._animation.on(Animation.EventType.FINISHED, () => {
                    this.isAttacking = false;
                });

                // this._animation!.on(Animation.EventType.STOP, () => {
                //     this.isAttacking = false;
                // }, this);

                this._animation.play('gong');
            }
        }
    }
    move(deltaTime: number) {
        if(GameManager.instance.getGameStatus() != 1) {
            if (this._animation && this._animation.clips.some(clip => clip.name === 'run')) {
                this._animation.play('zhan');
            } 
            
            return
        };

         // 获取当前位置和目标位置
        const currentPos = this.node.worldPosition;
        const targetPos = this.target.worldPosition;
        // 计算方向向量
        const direction = new Vec3();
        Vec3.subtract(direction, targetPos, currentPos);
        //  log('方向向量',direction)

        if (Vec3.len(direction) > 120) {
            if(this.isMoveing == false){
                if (this._animation && this._animation.clips.some(clip => clip.name === 'run')) {
                    this._animation.play('run');
                }
            }
            this.isMoveing = true;
        }
        if (Vec3.len(direction) < 80) {
            if(!this.isMoveing){
                // log('敌人开始攻击')
                this.gongji()
            }
            this.isMoveing = false;
        }
        if(!this.isMoveing) return;

        // 归一化方向向量
        Vec3.normalize(direction, direction);
        //   log('归一化方向向量',direction)

         //根据方向 动起来
        if(direction.x!=0){
            let num=0
            if(direction.x > 0){
                num=1
            }else{
                num=-1
            }
            //改变缩放方向
            this.node.setScale(this.node.scale.y * num,this.node.scale.y,1);
            //移动过去
            this.node.x= this.node.x + num * this.moveSpeed*deltaTime;

        }
        if(direction.y!=0){
          //  this.node.y= this.node.y+direction.y * this.moveSpeed*deltaTime;
        }
    }
    update(deltaTime: number) {
        if(!this.isStart) return;
        this.move(deltaTime);
    }
    onDestroy() {
        if (this.attackCollider) {
            this.attackCollider.off(Contact2DType.BEGIN_CONTACT, this.onAttackHit, this);
        }
        GlobalEvent.targetOff(this);
    }
}


